<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\v1\controller;

use api\v1\model\Advertise;
use api\v1\model\Article;
use api\v1\model\Category;
use api\v1\model\Lottery;
use api\v1\model\Option;
use api\v1\model\Order;
use api\v1\model\Product;
use api\v1\model\Smslog;
use api\v1\model\User;
use cmf\controller\RestBaseController;
use cmf\lib\Upload;
use think\facade\Db;

/**
 * 首页接口
 * Class IndexController
 * @package api\v1\controller
 */
class PublicController extends RestBaseController
{
    public function login() {
        $data = $this->request->post();
        $user = User::where("user_login",$data['user_login'])->find();
        if(!$user) {
            $this->error("用户不存在");
        }
        if(cmf_compare_password($data['user_pass'],$user->user_pass)){
            $this->success('登录成功！',['token'=>cmf_generate_user_token($user->id,$this->deviceType)]);
        }
        $this->error("用户名或密码错误");
    }

    public function register() {
        $data = $this->request->post();
        $this->validateFailError($data,[
            "mobile"=>'require|mobile',
            "code"=>'require',
            //"invite_code"=>'required',
            "password"=>"require"
        ]);
        $pid = 0;
        $path = "";
        $parent = User::where("invite_code",$data['invite_code'])
            ->where("user_status",1)
            ->where("user_type",2)
            ->find();
        if($parent) {
            $pid = $parent->id;
            $path = ($parent->path ? $parent->path . ",":"") . $parent->id;
        }
        else {
            // $this->error("邀请码错误");
        }
        if(!cmf_check_verification_code($data['mobile'],$data['code'])) {
            $this->error("验证码错误");
        }
        User::create([
            'user_login'=>$data['mobile'],
            'user_pass'=>cmf_password($data['password']),
            'pid'=>$pid,
            'path'=>$path,
            'user_type'=>2,
            'user_nickname'=>substr($data['mobile'],0,3)."****".substr($data['mobile'],strlen($data['mobile'])-4),
            'invite_code'=>$this->genCode(6),
            'create_time'=>time(),
            'mobile'=>$data['mobile']

        ]);
        $this->success("注册成功");
    }
    private function genCode($len)
    {
        $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $code = "";
        for ($i = 0; $i < $len; $i++) {
            $code .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        $has = User::where("invite_code", $code)->count();
        if ($has > 0) {
            $code = $this->genCode($len);
        }
        return $code;
    }

    public function sendCode() {
        $mobile = $this->request->post("mobile");
        $type = $this->request->post("type","0");
        /*
        $ip = $this->request->ip();
        $last = Smslog::where("mobile",$mobile)
            ->where('type',$type)
            //->where("ip",$ip)
            ->order("add_time","desc")
            ->find();
        if($last && ($last->add_time + 60) > time()) {
            $this->error("请稍后重试");
        }
       // Smslog::create(['mobile'=>$mobile,'add_time'=>time(),'code'=>$code,'ip'=>$ip,'type'=>$type]);
        $code = str_pad(mt_rand(0,9999),4,0,STR_PAD_LEFT);
        */
        if($code = cmf_get_verification_code($mobile)) {
            cmf_verification_code_log($mobile, $code, time() + 300);
            //$this->success('发送成功');
            $this->success($code);
        }
        $this->error("超过每日限额",$code);
    }
    public function upload() {
        $uploader = new Upload();

        $result = $uploader->upload();

        if ($result === false) {
            $this->error($uploader->getError());
        } else {
            $this->success("上传成功!", cmf_get_image_url($result['filepath']));
        }
    }
    public function siteInfo() {
        $this->success('ok',Option::where("option_name",'site_info')->find()->option_value);
    }
    //每日00：00执行;16:00之前购买，第二天计算收益；以后够买，则第三天计算收益
    public function calc() {
        $token="acbddfdtet144555tgr4wedsretgt4etfdfsd";
        if($token == $this->request->param("token")) {
            $last_calc_time = strtotime("today") - 60*60*9;
            $this_calc_time = $last_calc_time + 60 * 60 * 24;
            $orders = Order::with("product")->where("status",1)
                ->where("useritem_time","<",$last_calc_time+3600)
                ->select();
            foreach($orders as $order) {
                $user = User::with("level")->where('id',$order->user_id)->find();
                if($order->shichang > $order->sendday_count) {
                    $level_rate = $user->level->rate;
                    $shouyi = intval($order->amount * ($order->rate * (1 + ($level_rate + $order->fenhong) / 100))) / 100;
                    //未计算收益天数，正常情况应为1
                    $days = intval((time() - $order->useritem_time)/(60*60*24));
                    if(($order->sendday_count + $days)>$order->shichang) {
                        $days = $order->shichang - $order->sendday_count;
                    }
                    $shouyi = $shouyi * $days;
                    $order->benefit = $order->benefit + $shouyi;
                    $order->sendday_count = $order->sendday_count + $days;
                    $order->useritem_time = $this_calc_time;
                    if($order->shichang <= $order->sendday_count) {
                        $order->status = 0;
                        //收益
                        User::money_change($order->user_id,$order->benefit,8,$order->product?($order->product->id.":".$order->product->title):"");
                        //本金
                        User::money_change($order->user_id,$order->amount,7,$order->product?($order->product->id.":".$order->product->title):"");
                    }
                    $order->save();
                    $user->shouyi = $user->shouyi + $shouyi;
                    $user->save();
                }
            }
            $users = User::where('user_type',2)->where("user_status",1)->select();
            foreach($users as $user) {
                if ($user->yeb_add_time < strtotime("today")) {
                    $user->yeb_enabled = $user->yeb;
                }
                if ($user->yeb_enabled > 0) {
                    $site_info = Option::where("option_name", "site_info")->find()->option_value;
                    if (isset($site_info['bank_rate'])) {
                        $rate = floatval($site_info['bank_rate']);
                        if ($rate > 0) {
                            $shouyi = intval($user->yeb_enabled * $rate) / 100;
                            if ($shouyi > 0) {
                                User::money_change($user->id, $shouyi, 9, "");
                            }
                        }
                    }
                }
            }
        }
    }
}
